package com.sgy.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sgy.dao.AccountMapper;
import com.sgy.pojo.Account;
import com.sgy.pojo.UserInfo;
import com.sgy.rocketMQ.OfflineInfoTransmit;
import com.sgy.util.NettyUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sgy
 * @description Channel的管理器以及user管理工具类
 */
@Component
public class UserInfoManager {

    private static final Logger logger = LoggerFactory.getLogger(UserInfoManager.class);

    //记录当前用户与通道Map
    public static ConcurrentMap<String, UserInfo> userChannelMap=new ConcurrentHashMap();

    private static AtomicInteger userCount = new AtomicInteger(0);

    @Resource
    private AccountMapper accountMapper;
    private static AccountMapper accountMapperStatic;

    @Resource
    private OfflineInfoTransmit offlineInfoTransmit;
    private static OfflineInfoTransmit offlineInfoTransmitStatic;

    @PostConstruct
    public void init(){
        accountMapperStatic = accountMapper;
        offlineInfoTransmitStatic = offlineInfoTransmit;
    }
    //用户登录添加用户账号以及所对应的通道
    public static void addChannel(Channel channel,String username){
        String remoteAddr = NettyUtil.parseChannelRemoteAddr(channel);
        if(!channel.isActive()){
            logger.error("channel is not active, address: {}", remoteAddr);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setAddr(remoteAddr);
        userInfo.setChannel(channel);
        userInfo.setTime(System.currentTimeMillis());
        userChannelMap.put(username,userInfo);
    }

    //登录验证用户名密码
    public static boolean saveUser(Channel channel,String username,String password){
        UserInfo userInfo = userChannelMap.get(username);
        if(userInfo == null){
            return false;
        }
        if(!userChannelMap.containsKey(username)){
            return false;
        }
        if(!channel.isActive()){
            logger.error("channel is not active, address: {}, username: {}");
            return false;
        }
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return false;
        }
        Account account = accountMapperStatic.selectUsernameAndPassword(username);
        if(account==null){
            return false;
        }
        if(!password.equals(account.getPassword())){
            return false;
        }
        //增加一个认证用户
        userCount.incrementAndGet();
        userInfo.setId(account.getId());

        // 注册该用户推送消息的通道
        offlineInfoTransmitStatic.registerPull(channel,account.getId());
        return true;
    }

    //单聊
    public static void p2p(String sender,String reciver,String message){
//        Map map = new HashMap();
//        map.put("type",2);
//        map.put("username",sender);
//        map.put("mess",message);
        JSONObject data = new JSONObject();
        data.put("type",2);
        data.put("username",sender);
        data.put("mess",message);
        System.out.println(data.toString());
        System.out.println(data);
        if(StringUtils.isNotEmpty(message)){
            if(userChannelMap.containsKey(reciver)){
                userChannelMap.get(reciver).getChannel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(data)));
            }else {
                Account account = accountMapperStatic.selectUidByusername(reciver);
                if(account!=null){
                    offlineInfoTransmitStatic.pushP2P(account.getId(),data);
                }
            }
        }

    }
}
